<template>
    <div class="vxe_table_container" :style="{ width: tableWidth }">
        <template v-if="tableOptions.toolbarConfig">
            <vxe-toolbar size="mini" :size="tableOptions.toolbarConfig.size"
                         :import="tableOptions.toolbarConfig.import"
                         :export="tableOptions.toolbarConfig.export"
                         :print="tableOptions.toolbarConfig.print"
                         :refresh="tableOptions.toolbarConfig.refresh"
                         :custom="tableOptions.toolbarConfig.custom"
                         :buttons="tableOptions.toolbarConfig.buttons" />
        </template>
        <vxe-table :id="'vxeTable-' + tableOptions.ref" class="table" :ref="tableOptions.ref"
                   :data="data" :height="tableOptions.height" :max-height="tableOptions.maxHeight"
                   :auto-resize="tableOptions.autoResize" :sync-resize="tableOptions.syncResize"
                   :keep-source="tableOptions.keepSource" :resizable="tableOptions.resizable"
                   :stripe="tableOptions.stripe" :border="tableOptions.border"
                   :size="tableOptions.size" :loading="tableOptions.loading"
                   :align="tableOptions.align" :header-align="tableOptions.headerAlign"
                   :footer-align="tableOptions.footerAlign" :show-header="tableOptions.showHeader"
                   :header-cell-class-name="tableOptions.headerCellClassName"
                   :row-id="tableOptions.rowId" :key="tableOptions.ref"
                   :highlight-current-row="tableOptions.highlightCurrentRow"
                   :highlight-hover-row="tableOptions.highlightHoverRow"
                   :highlight-current-column="tableOptions.highlightCurrentColumn"
                   :highlight-hover-column="tableOptions.highlightHoverColumn"
                   :row-class-name="tableOptions.rowClassName"
                   :cell-class-name="tableOptions.cellClassName"
                   :show-footer="tableOptions.showSummary"
                   :footer-method="tableOptions.footerMethod"
                   :merge-cells="tableOptions.mergeCells"
                   :merge-footer-items="tableOptions.mergeFooterItems"
                   :show-overflow="tableOptions.showOverflow"
                   :column-config="tableOptions.columnConfig"
                   :row-config="tableOptions.rowConfig"
                   :seq-config="tableOptions.seqConfig"
                   :sort-config="tableOptions.sortConfig"
                   :filter-config="tableOptions.filterConfig"
                   :export-config="tableOptions.exportConfig"
                   :import-config="tableOptions.importConfig"
                   :print-config="tableOptions.printConfig"
                   :radio-config="tableOptions.radioConfig"
                   :checkbox-config="tableOptions.checkboxConfig"
                   :tooltip-config="tableOptions.tooltipConfig"
                   :expand-config="tableOptions.expandConfig"
                   :tree-config="tableOptions.treeConfig"
                   :context-config="tableOptions.contextConfig"
                   :mouse-config="tableOptions.mouseConfig"
                   :keyboard-config="tableOptions.keyboardConfig"
                   :edit-config="tableOptions.editConfig"
                   :valid-config="tableOptions.validConfig"
                   :edit-rules="tableOptions.editRules"
                   :custom-config="tableOptions.customConfig"
                   :empty-render="tableOptions.emptyRender"
                   :empty-text="tableOptions.emptyText"
                   :scroll-x="tableOptions.scrollX"
                   :scroll-y="tableOptions.scrollY"
                   :class="{ hide_select_all: hideSelectAll }"
                   :min-height="tableOptions.minHeight"
                   @checkbox-change="handleSelectionChange"
                   @radio-change="handleRadioChange"
                   @checkbox-all="handleSelectionChange"
                   @cell-click="handleCellClick"
                   @cell-dblclick="handleCellDblClick"
                   @keydown="handleKeydown"
                   @current-change="handleCurrentChange"
                   @resizable-change="handleResizableChange"
                   @custom="handleCustomEvent"
                   @sort-change="handleSortChange"
                   :span-method="spanMethod"
                   v-get-ref="getRefFn">
            <!--数据列-->
            <template v-for="(item, index) in tableOptions.columns">
                <base-vxe-table-children-column v-if="item.children && item.children.length > 0"
                                                :key="index" :index="index" :col="item"
                                                :edit="tableOptions.edit" />
                <template v-else>
                    <template v-if="item.render || item.renderHeader || item.formatter || item.elComp">
                        <base-vxe-table-column-render :key="index" :index="index" :col="item"
                                               :edit="tableOptions.edit" />
                    </template>
                    <template v-else>
                        <base-vxe-table-column :key="index" :index="index" :col="item"
                                               :edit="tableOptions.edit" />
                    </template>
                </template>
            </template>
            <!--按钮操作组-->
            <base-vxe-operate-column :operates="tableOptions.operates" />
        </vxe-table>
        <template v-if="tableOptions.pagination">
            <pagination :option="tableOptions.pagination"
                        :render="tableOptions.pagination.render"
                        :event="paginationEvent" />
        </template>
        <table-export ref="tableExport" :tableOptions="tableOptions" />
        <!-- 监听高度变化 -->
        <resize-sensor initial @resize="handleResizeEvent" />
    </div>
</template>

<script>
import "./render";
import TableExport from "./export/export";
import Pagination from "../custom/Pagination";
import BaseVxeTableColumn from "./components/BaseVxeTableColumn";
import BaseVxeTableColumnRender from "./components/BaseVxeTableColumnRender";
import BaseVxeTableChildrenColumn from "./components/BaseVxeTableChildrenColumn";
import BaseVxeOperateColumn from "./components/BaseVxeOperateColumn";
import ResizeSensor from 'vue-resize-sensor';
import inject from "@common/mixins/inject";
import {eachTableField, exportExcel4MultiHead} from "@common/utils/excel";

export default {
    extends: inject,
    props: {
        data: {
            type: Array,
            default() {
                return [];
            },
        },
        options: {
            type: Object,
            default() {
                return {
                    init: true,
                };
            },
        },
    },
    components: {
        ResizeSensor,
        TableExport,
        BaseVxeTableColumn,
        BaseVxeTableColumnRender,
        BaseVxeTableChildrenColumn,
        BaseVxeOperateColumn,
        Pagination,
        expandDom: {
            functional: true,
            props: {
                row: Object,
                render: Function,
                index: Number,
                column: {
                    type: Object,
                    default: null,
                },
            },
            render: (h, ctx) => {
                const params = {
                    row: ctx.props.row,
                    index: ctx.props.index,
                };
                if (ctx.props.column) {
                    params.column = ctx.props.column;
                }
                if (typeof ctx.props.render === 'function') {
                    return ctx.props.render(h, params);
                }
            },
        },
        expandHeader: {
            functional: true,
            props: {
                row: Object,
                headerRender: Function,
                index: Number,
                column: {
                    type: Object,
                    default: null,
                },
            },
            render: (h, ctx) => {
                const params = {
                    row: ctx.props.row,
                    index: ctx.props.index,
                };
                if (ctx.props.column) {
                    params.column = ctx.props.column;
                }
                if (ctx.props.headerRender) {
                    return ctx.props.headerRender(h, params);
                } else {
                    return h("span", ctx.props.column.label);
                }
            },
        },
        popover: {
            functional: true,
            props: {
                content: Function,
                column: {
                    type: Object,
                    default: null,
                },
            },
            render: (h, ctx) => {
                return ctx.props.content(h, ctx.props.column);
            },
        },
    },
    data() {
        const _this = this;
        return {
            tableOptions: {},
            tableSearchCache: [],
            defaultOptions: {
                selectFixed: "left",
                indexFixed: "left",
                summaryLabel: "合计",
                keepSource: false, //保持原始值的状态，被某些功能所依赖，比如编辑状态、还原数据等（开启后影响性能，具体取决于数据量）
                autoResize: true, //自动监听父元素的变化去重新计算表格
                syncResize: false, //自动跟随某个属性的变化去重新计算表格，和手动调用 recalculate 方法是一样的效果
                resizable: true, //所有的列是否允许拖动列宽调整大小
                stripe: false, //是否带有斑马纹
                border: "full", //是否带有边框default（默认）, full（完整边框）, outer（外边框）, inner（内边框）, none（无边框）
                size: "mini", //
                loading: false, //表格是否显示加载中
                align: "center", //所有的列对齐方式left（左对齐）, center（居中对齐）, right（右对齐
                headerAlign: "center", //所有的表头列的对齐方式,继承 align
                footerAlign: "center", //
                showHeader: true, //是否显示表头
                highlightCurrentRow: false, //是否要高亮当前行
                highlightHoverRow: true, //鼠标移到行是否要高亮显示
                highlightCurrentColumn: false, //
                highlightHoverColumn: false, //
                // rowClassName:false,//给行附加 className //string | (({ row, rowIndex, $rowIndex }) => any)
                showFooter: false, //
                footerMethod: this.footerMethod, //表尾的数据获取方法，返回一个二维数组({ columns, data }) => any[][]
                // mergeCells:[],//临时合并指定的单元格（不能用于树形结构、展开行，不建议用于固定列）Array<{ row: number, col: number, rowspan: number, colspan: number }>
                // mergeFooterItems:[],//临时合并表尾（不能用于树形结构、展开行,不建议用于固定列）
                // rowKey:false,//是否需要为每一行的 VNode 设置 key 属性（非特殊情况下没必要设置）
                mouseConfig: { selected: true },
                editRules: {}, //校验规则
                editConfig: {
                    trigger: "click",
                    mode: "cell",
                    icon: "fa fa-pencil",
                    showIcon: true,
                    beforeEditMethod: this.handleEditActived,
                }, //
                keyboardConfig: {
                    isArrow: true,
                    isDel: true,
                    isEnter: true,
                    isEdit: true,
                    enterToTab: true,
                    // editMethod:this.editMethod,//重写默认的覆盖式，改为追加式
                },
                radioConfig: {
                    trigger: 'row',
                },
                checkboxConfig: {
                    trigger: 'row',
                },
                showOverflow: true, //
                operates: {
                    fixed: "right",
                    list: [],
                },
                pagination: false,
                cellStyle({ row, column, rowIndex, columnIndex }) {
                },
                getMaxHeight() {
                    return undefined;
                },
                exportConfig: {
                    visible: false,
                    title: "导出参数配置", //导出弹框标题
                    showDialog: true, //是否显示导出弹框
                    url: "", //请求数据url
                    queryData: "", //请求数据搜索条件
                    filename: document.title, //导出默认文件名
                    convert: {
                        //数据字典转换
                    },
                },
                customConfig: {
                    checkMethod({ column }) {
                        return ['_section', '_radio', '_index', 'operates'].indexOf(column.field) === -1;
                    },
                },
                sortConfig:{remote:true,multiple:true},
            },
            defaultTooltip: {
                effect: "dark", //默认提供的主题-dark/light
                placement: "top", //Tooltip 的出现位置-top/top-start/top-end/bottom/bottom-start/bottom-end/left/left-start/left-end/right/right-start/right-end
                content: "", //显示的内容
                disabled: false, //Tooltip 是否可用
                offset: 0, //出现位置的偏移量
                transition: "el-fade-in-linear", //定义渐变动画
                visibleArrow: true, //是否显示 Tooltip 箭头
                popperOptions: {}, //popper.js 的参数
                openDelay: 0, //延迟出现，单位毫秒
                manual: false, //手动控制模式，设置为 true 后，mouseenter 和 mouseleave 事件将不会生效
                popperClass: "", //为 Tooltip 的 popper 添加类名
                enterable: false, //鼠标是否可进入到 tooltip 中
                hideAfter: 0, //Tooltip 出现后自动隐藏延时，单位毫秒，为 0 则不会自动隐藏
            },
            defaultPagination: {
                layout: 'total, sizes, prev, pager, next, jumper',
                total: 0,
                pagerCount: 7,
                totalPage: 0,
            },
            paginationEvent: {
                sizeChange: _this.handleSizeChange,
                currentChange: _this.handleIndexChange,
            },
            popoverOptions: {},
            filter: () => {
                return true;
            },
            checkboxColumn: {
                width: 50,
                type: 'checkbox',
                prop: '_section',
                align: 'center',
            },
            radioColumn: {
                width: 50,
                type: 'radio',
                prop: '_radio',
                align: 'center',
            },
            indexColumn: {
                width: 50,
                type: 'seq',
                label: '序号',
                prop: '_index',
                align: 'center',
            },
        };
    },
    computed: {
        tableWidth() {
            if (this.tableOptions.width !== undefined) {
                if (typeof this.tableOptions.width === "number") {
                    return `${ this.tableOptions.width }px`;
                } else {
                    return this.tableOptions.width;
                }
            }
            return "100%";
        },
        hideSelectAll() {
            if (typeof this.tableOptions.isDisable === "function") {
                let dataList = this.data || [];
                let filter = dataList.filter(
                    (item) => !this.tableOptions.isDisable(item)
                );
                return filter.length > 0;
            }
            return false;
        },
        currentTableSetting() {
            let tableSetting = (this.$store.state.table_setting || []).map(item => $.extend({}, item));
            let filter = tableSetting.filter(item => item.router_path === this.$route.fullPath && item.type === this.tableOptions.ref);
            if (this.$utils.isNotEmptyList(filter)) {
                return {
                    columns: JSON.parse(filter[0].columns_json || '[]'),
                    pagination: JSON.parse(filter[0].page_json || '{}'),
                };
            }
            return {};
        },
    },
    watch: {
        options: {
            handler() {
                this.initTableOptions(this.options);
            },
            deep: true,
            immediate: true,
        },
        data: function (value, oldValue) {
            this.reloadData(value, oldValue, 0);
        },
    },
    methods: {
        handleResizeEvent() {
            this.resizeTable();
            this.$emit("event", { type: 'resize' });
        },
        getRefFn(c) {
            typeof this.setChildrenRef === 'function' && this.setChildrenRef(this.tableOptions.ref, c);
        },
        reloadData(data, old, type = 1) {
            // type:1表示进行vxe-table的原始方法,加载数据并清除所有状态；0表示数据监听data变化触发并checkbox-change事件
            let ref = this.$refs[this.tableOptions.ref];
            if (type === 1) {
                ref.reloadData(data);
            }
            // let dataInstanceChanged = data !== old;
            // if (type === 0 && dataInstanceChanged && this.tableOptions.multiSelect) {
            //     return this.handleSelectionChange({ records: [] });
            // }
        },
        getBtnField(field, row, scope) {
            if (typeof field === "function") {
                field = field(row, scope);
            }
            return field;
        },
        handleKeydown(params) {
            // const { $event, $table } = params
            // console.log('handleKeydown',params,$event)
        },
        handleEditActived(params) {
            const { rowIndex, row } = params;
            // console.log('handleEditActived',params,this.tableOptions,this.tableOptions.edit===false)
            return this.tableOptions.edit !== false;
        },
        handleSortChange(params){
            // const {column, field, order, sortBy, sortList, $event} = params;
            const sortList = (params.sortList || []).map(item => {
                return {
                    field: item.field,
                    order: item.order,
                };
            })
            this.tableOptions = $.extend({}, this.tableOptions, { sortList });
            let options = $.extend({}, this.options, { sortList });
            this.$emit('update:options', options);
            this.$emit("event", { type: "sortChange", ...params, });
        },
        editMethod({ row, column }) {
            // 重写默认的覆盖式，改为追加式
            let ref = this.$refs[this.tableOptions.ref];
            ref.setActiveCell(row, column.property);
            //返回 false 阻止默认行为
            return false;
        },
        footerMethod({ columns, data }) {
            let $this = this;
            return [
                columns.map((column, columnIndex) => {
                    if (
                        columnIndex === 0 &&
                        [ "_section", "_radio" ].indexOf(column.property) === -1
                    ) {
                        return $this.tableOptions.summaryLabel;
                    }
                    if (column.property === "_index") {
                        return $this.tableOptions.summaryLabel;
                    }
                    if (
                        $this.tableOptions.summaryArray &&
                        $this.tableOptions.summaryArray.includes(column.property)
                    ) {
                        return $this.$XEUtils.sum(data, column.property);
                    }
                    return null;
                }),
            ];
        },
        resizeTable() {
            let _this = this;
            this.$nextTick(() => {
                let maxH = _this.tableOptions.getMaxHeight();
                if (maxH) {
                    _this.tableOptions = $.extend({}, _this.tableOptions, {
                        maxHeight: maxH,
                    });
                } else {
                    let hasTabs = $("#app").find(".tabs_wrapper").length > 0;
                    if (hasTabs) {
                        this.resizeTabsTable();
                    } else {
                        if (_this.$utils.isNotEmpty(_this.tableOptions.container)) {
                            let maxHeight = $("#app").find(".app_content").height();
                            let cardHeader = $(_this.tableOptions.container).find(".el-card__header");
                            if (cardHeader.length > 0) {
                                let chHeight = cardHeader.outerHeight();
                                if (chHeight < 52) {
                                    chHeight = 52;
                                }
                                maxHeight -= chHeight;
                            }
                            let buttons = $(_this.tableOptions.container).find(".buttons");
                            if (buttons.length > 0) {
                                maxHeight -= buttons.outerHeight();
                            }
                            if (_this.tableOptions.pagination) {
                                let pagination = $(".vxe_table_container").find(".el-pagination");
                                if (pagination.length > 0) {
                                    maxHeight -= pagination.outerHeight() + 35;
                                }
                                maxHeight -= 12;
                            } else {
                                maxHeight -= 24;
                            }
                            let tableFooter = $(_this.tableOptions.container).find('.vxe_table_container').find('.vxe-table--footer');
                            if (tableFooter && tableFooter.length > 0) {
                                maxHeight -= $(tableFooter).outerHeight();
                            }
                            if (_this.tableOptions.subHeight) {
                                maxHeight -= _this.tableOptions.subHeight;
                            }
                            if (maxHeight > 0) {
                                _this.tableOptions = $.extend({}, _this.tableOptions, {
                                    maxHeight: maxHeight,
                                });
                            }
                        }
                    }
                    let paginationHeight = $(".el-dialog__body").find(".vxe_table_container").find(".el-pagination").height();
                    if (paginationHeight) {
                        let vxeTableContainer = $(".el-dialog__body").find(".vxe_table_container");
                        vxeTableContainer.css("padding-bottom", "32px");
                    }
                    // let ref = this.$refs[this.tableOptions.ref];
                    // ref.refreshColumn()
                    // ref.reloadData(this.data)
                }
            });
        },
        resizeTabsTable() {
            let _this = this;
            let tabContainer = _this.getActiveTabsContainer();
            if (_this.$utils.isNotEmpty(_this.tableOptions.container)) {
                let tableContainer = $(tabContainer).find(_this.tableOptions.container);
                let maxHeight = $(tableContainer).height();
                let cardHeader = $(tableContainer).find(".el-card__header");
                if (cardHeader.length > 0) {
                    let chHeight = cardHeader.outerHeight();
                    if (chHeight < 45) {
                        chHeight = 45;
                    }
                    maxHeight -= chHeight;
                    const headerContraction = $(cardHeader).find('.my-contraction');
                    if (headerContraction && headerContraction > 0) {
                        maxHeight -= headerContraction.outerHeight();
                    }
                }
                let cardBody = $(tableContainer).find(".el-card__body");
                if (cardBody && cardBody.length > 0) {
                    let paddingTop = $(cardBody).css('padding-top');
                    if (paddingTop) {
                        maxHeight -= Number(paddingTop.replace('px', ''));
                    }
                    let paddingBottom = $(cardBody).css('padding-bottom');
                    if (paddingBottom) {
                        maxHeight -= Number(paddingBottom.replace('px', ''));
                    }
                }
                let buttons = $(cardBody).find(".buttons");
                if (buttons.length > 0) {
                    maxHeight -= buttons.outerHeight() + 10;
                }
                // let vxeTableContainer = $(cardBody).find(".vxe_table_container");
                // let contraction = $(cardHeader).find(".my-contraction");
                // if (contraction && contraction.length > 0 && buttons.length === 0) {
                //     vxeTableContainer.css("margin-top", "25px");
                //     maxHeight -= 40;
                // }
                // if (contraction && contraction.length > 0 && buttons.length > 0) {
                //     vxeTableContainer.css("margin-top", "0px");
                // }
                if (_this.tableOptions.pagination) {
                    let pagination = $(tableContainer).find(".vxe_table_container").find(".el-pagination");
                    if (pagination && pagination.length > 0) {
                        maxHeight -= pagination.outerHeight();
                    }
                }
                if (_this.tableOptions.subHeight) {
                    maxHeight -= _this.tableOptions.subHeight;
                }
                let scrollX = $(tableContainer).find(".vxe_table_container").find(".scroll--x");
                if (scrollX && scrollX.length > 0) {
                    maxHeight -= $(scrollX).outerHeight();
                }
                let tableFooter = $(tableContainer).find('.vxe_table_container').find('.vxe-table--footer');
                if (tableFooter && tableFooter.length > 0) {
                    maxHeight -= $(tableFooter).outerHeight();
                }
                let cardFoot = $(tableContainer).find(".card-foot");
                if (cardFoot && cardFoot.length > 0) {
                    maxHeight -= 50;
                }
                maxHeight += 8;
                maxHeight -= 10;
                if (maxHeight > 0) {
                    _this.tableOptions = $.extend({}, _this.tableOptions, {
                        maxHeight: maxHeight,
                    });
                }
            }
        },
        initTableOptions(options) {
            let _this = this;
            _this.initTableColumns(options);
            this.tableSearchCache = [];
            let operates = $.extend({}, this.tableOptions.operates);
            operates.list = this.initTableOperates(operates.list)
            if (_this.$utils.isNotEmptyList(operates.list)) {
                let width = 15;
                if (_this.$utils.isNotEmpty(operates.count) && operates.count > 0) {
                    let opWidth = _this.$utils.accMul(30, operates.count);
                    width = Number(_this.$utils.accAdd(width, opWidth));
                } else {
                    operates.list.forEach((item) => {
                        if (item.show) {
                            width += 30;
                            if (item.filter === undefined) {
                                item.filter = this.filter;
                            }
                        }
                    });
                }
                operates.width = _this.$utils.isNotEmpty(operates.width) ? operates.width : width;
            }
            if (this.tableOptions.edit !== undefined && this.tableOptions.edit !== true) {
                this.tableOptions.editConfig.showIcon = false;
                this.tableOptions.mouseConfig.selected = false;
            }
            this.tableOptions = $.extend({}, this.tableOptions, {
                operates,
                mouseConfig: $.extend({}, this.defaultOptions.mouseConfig, this.tableOptions.mouseConfig),
                editConfig: $.extend({}, this.defaultOptions.editConfig, this.tableOptions.editConfig),
                exportConfig: $.extend({}, this.defaultOptions.exportConfig, this.tableOptions.exportConfig),
                printConfig: $.extend({}, this.defaultOptions.printConfig, this.tableOptions.printConfig),
                checkboxConfig: $.extend({}, this.defaultOptions.checkboxConfig, this.tableOptions.checkboxConfig),
                radioConfig: $.extend({}, this.defaultOptions.radioConfig, this.tableOptions.radioConfig),
            });
            _this.$nextTick(() => {
                _this.resizeTable();
            });
        },
        initTableColumns(options) {
            let _this = this;
            let opt = $.extend({}, options);
            delete opt.columns;
            this.tableOptions = $.extend({}, _this.defaultOptions, opt);
            if (_this.tableOptions.selectFixed === "none") {
                delete _this.tableOptions.selectFixed;
            }
            if (this.tableOptions.indexFixed === "none") {
                delete _this.tableOptions.indexFixed;
            }
            let columns = [];
            if (_this.tableOptions.multiSelect) {
                let checkboxColumn = $.extend({}, _this.checkboxColumn, {
                    selectable: _this.tableOptions.isDisable,
                    fixed: _this.tableOptions.selectFixed,
                })
                if (_this.$utils.isNotEmpty(_this.tableOptions.checkboxWidth)) {
                    checkboxColumn.width = _this.tableOptions.checkboxWidth;
                }
                columns.push(checkboxColumn);
            } else if (_this.tableOptions.radioSelect) {
                let radioColumn = $.extend({}, _this.radioColumn, {
                    selectable: _this.tableOptions.isDisable,
                    fixed: _this.tableOptions.selectFixed,
                    renderHeader: _this.tableOptions.radioHeader,
                })
                if (_this.$utils.isNotEmpty(_this.tableOptions.radioWidth)) {
                    radioColumn.width = _this.tableOptions.radioWidth;
                }
                columns.push(radioColumn);
            }
            if (!_this.tableOptions.hideIndex) {
                let indexColumn = $.extend({}, _this.indexColumn, {
                    fixed: _this.tableOptions.indexFixed,
                });
                if (typeof this.tableOptions.formatterIndex === 'function') {
                    indexColumn.formatter = (row, column, scope) => {
                        let pagination = $.extend({}, _this.tableOptions.pagination);
                        return _this.tableOptions.formatterIndex({row, column, scope}, pagination);
                    };
                } else {
                    if (this.tableOptions.pagination) {
                        indexColumn.formatter = (row, column, scope) => {
                            let pagination = $.extend({}, _this.tableOptions.pagination);
                            return pagination.pageSize * (pagination.pageIndex - 1) + scope.rowIndex + 1;
                        };
                    } else {
                        indexColumn.formatter = (row, column, scope) => {
                            return scope.rowIndex + 1;
                        };
                    }
                }
                if (_this.$utils.isNotEmpty(_this.tableOptions.indexWidth)) {
                    indexColumn.width = _this.tableOptions.indexWidth;
                }
                columns.push(indexColumn);
            }
            if (options.columns) {
                columns = columns.concat(options.columns.map(item => $.extend({}, item)));
            }
            if (_this.currentTableSetting.columns && !_this.currentTableSetting.pagination.reset) {
                columns = _this.filterColumns4TableSetting(columns);
            }
            _this.tableOptions = $.extend({}, _this.tableOptions, { columns });
            if (_this.tableOptions.pagination) {
                let pagination = $.extend({}, _this.defaultPagination, _this.tableOptions.pagination);
                let size = _this.$utils.getSessionStorage("pageSize", _this.$route.path);
                if (_this.$utils.isEmpty(pagination.pageSize) && _this.$utils.isNotEmpty(size)) {
                    pagination.pageSize = size;
                }
                if (_this.currentTableSetting.pagination && _this.$utils.isNotEmpty(_this.currentTableSetting.pagination.pageSize)) {
                    pagination.pageSize = _this.currentTableSetting.pagination.pageSize;
                }
                if (_this.$utils.isEmpty(pagination.pageSize)) {
                    pagination.pageSize = window.configs.pageSize;
                }
                if (!_this.$utils.isNotEmptyList(_this.tableOptions.pagination.pageArray)) {
                    pagination.pageArray = window.configs.pageSizes;
                }
                _this.tableOptions = $.extend({}, _this.tableOptions, { pagination });
                // 缓存分页
                _this.setLocalPage(pagination.pageSize);
            }
        },
        filterColumns4TableSetting(columns) {
            const _this = this;
            let list = [];
            if (_this.$utils.isNotEmptyList(columns)) {
                columns.forEach(col => {
                    let obj = $.extend({}, col);
                    let filter = (_this.currentTableSetting.columns || []).filter(item => item.prop === col.prop);
                    if (_this.$utils.isNotEmptyList(filter)) {
                        obj.visible = filter[0].visible;
                        if (filter[0].resizeWidth > 0) {
                            obj.width = filter[0].resizeWidth;
                        }
                    }
                    if (_this.$utils.isNotEmptyList(col.children)) {
                        obj.children = _this.filterColumns4TableSetting(col.children);
                    }
                    list.push(obj);
                });
            }
            return list;
        },
        initTableOperates(datas) {
            let list = [];
            if (datas && datas.length > 0) {
                datas.forEach((item) => {
                    let obj = $.extend({}, item);
                    if (item.tooltip && this.$utils.isNotEmpty(item.tooltip.content)) {
                        obj.tooltip = $.extend({}, this.defaultTooltip, item.tooltip);
                    }
                    list.push(obj);
                });
            }
            return list;
        },
        getColumnDatas(columns) {
            let list = [];
            if (columns && columns.length > 0) {
                columns.forEach((item) => {
                    let object = $.extend({}, item);
                    list.push(object);
                    if (item.children && item.children.length > 0) {
                        let childs = this.getColumnDatas(item.children);
                        if (childs.length > 0) {
                            childs.forEach((child) => {
                                list.push(child);
                            });
                        }
                    }
                });
            }
            return list;
        },
        getColumnOpt(property) {
            let columns = this.getColumnDatas(this.tableOptions.columns);
            let filter = columns.filter((item) => item.prop === property);
            return filter && filter.length > 0 ? filter[0] : {};
        },
        handleSelectionChange({ records }) {
            this.$emit("handleSelectionChange", records);
            this.$emit("event", { type: "selectionChange", value: records });
        },
        handleRadioChange({ row }) {
            this.$emit("handleRadioChange", row);
            this.$emit("event", { type: "radioChange", value: row });
        },
        handleCurrentChange({ row, }) {
            let item = row;
            this.$emit("handleCurrentChange", item);
            this.$emit("event", { type: "currentChange", value: item });
        },
        handleCellClick({ row, column, $event, }) {
            if (column.property === 'operates') {
                return;
            }
            let ref = this.$refs[this.tableOptions.ref];
            //点击行选中
            let checkSelectDisabled = true;
            if (typeof this.tableOptions.isDisable === "function") {
                checkSelectDisabled = this.tableOptions.isDisable(row);
            }
            if (typeof this.tableOptions.disabledClickSelectFn === 'function') {
                checkSelectDisabled = this.tableOptions.disabledClickSelectFn(row);
            }
            if (this.tableOptions.checkboxConfig && this.$utils.isNotEmpty(this.tableOptions.checkboxConfig.trigger) && this.tableOptions.checkboxConfig.trigger !== 'default') {
                checkSelectDisabled = false;
            }
            if (checkSelectDisabled && !this.tableOptions.disabledClickSelect &&
                (this.tableOptions.multiSelect || this.tableOptions.radioSelect) &&
                column.property !== "_section"
            ) {
                if (this.tableOptions.multiSelect) {
                    ref.toggleCheckboxRow(row);
                }
                if (this.tableOptions.radioSelect) {
                    ref.setRadioRow(row)
                }
            } else {
                if (column && column.property === "_radio") {
                    ref.setRadioRow(row)
                }
            }
            let columnOpt = this.getColumnOpt(column.property);
            this.$emit("handleCellClick", { ref, row, column, $event, columnOpt });
            this.$emit("event", { type: "cellClick", ref, row, column, $event, columnOpt, });
        },
        handleCellDblClick({ row, column, $event, }) {
            let ref = this.$refs[this.tableOptions.ref];
            let columnOpt = this.getColumnOpt(column.property);
            this.$emit("handleCellDblClick", { ref, row, column, $event, columnOpt });
            this.$emit("event", { type: "cellDblClick", ref, row, column, $event, columnOpt, });
        },
        load(tree, treeNode, resolve) {
            this.$emit("load", { tree: tree, treeNode: treeNode, resolve: resolve });
            this.$emit("event", { type: "load", tree, treeNode, resolve });
        },
        //切换每页显示的数量
        handleSizeChange(size) {
            if (this.tableOptions.pagination) {
                let pagination = $.extend({}, this.tableOptions.pagination, {
                    pageIndex: 1,
                    pageSize: size,
                });
                this.tableOptions = $.extend({}, this.tableOptions, { pagination });
                let options = $.extend({}, this.options, { pagination });
                this.$emit('update:options', options);
                this.$emit("handleChangePage", pagination);
                this.$emit("event", { type: "page", pagination, });
                this.setLocalPage(size);
            }
        },
        setLocalPage(size) {
            let pageSize = {};
            if (sessionStorage.pageSize) {
                pageSize = this.$utils.getSessionStorage("pageSize");
            }
            pageSize[this.$route.path] = size;
            this.$utils.setSessionStorage("pageSize", pageSize);
        },
        handleIndexChange(current) {
            if (this.tableOptions.pagination) {
                let pagination = $.extend({}, this.tableOptions.pagination, {
                    pageIndex: current,
                });
                this.tableOptions = $.extend({}, this.tableOptions, { pagination });
                let options = $.extend({}, this.options, { pagination });
                this.$emit('update:options', options);
                this.$emit("handleChangePage", pagination);
                this.$emit("event", { type: "page", pagination, });
            }
        },
        spanMethod({ row, column, rowIndex, columnIndex }) {
            if (this.tableOptions.spanMethod === undefined) {
                if (row.spanOption) {
                    let option = row.spanOption[column.property];
                    let hideField = row.spanOption.hideField;
                    if (hideField && hideField.length > 0) {
                        if (hideField.indexOf(column.property) !== -1) {
                            return {
                                rowspan: 0,
                                colspan: 0,
                            };
                        }
                    }
                    if (option) {
                        if (!option.rowspan) {
                            option.rowspan = 0;
                        }
                        if (!option.colspan) {
                            option.colspan = 0;
                        }
                        return option;
                    }
                }
            } else {
                this.tableOptions.spanMethod({ row, column, rowIndex, columnIndex });
            }
        },
        toggleRowSelection(row, selected) {
            if (this.$refs[this.tableOptions.ref]) {
                if (this.tableOptions.multiSelect) {
                    this.$refs[this.tableOptions.ref].setCheckboxRow(row, selected);
                }
                if (this.tableOptions.radioSelect) {
                    this.$refs[this.tableOptions.ref].setRadioRow(row);
                    if (this.tableOptions.rowConfig && this.tableOptions.rowConfig.isCurrent) {
                        this.$refs[this.tableOptions.ref].setCurrentRow(row);
                    }
                }
            }
        },
        clearSelection() {
            if (this.$refs[this.tableOptions.ref]) {
                if (this.tableOptions.multiSelect) {
                    this.$refs[this.tableOptions.ref].clearCheckboxRow();
                }
                if (this.tableOptions.radioSelect) {
                    this.$refs[this.tableOptions.ref].clearRadioRow();
                    if (this.tableOptions.rowConfig && this.tableOptions.rowConfig.isCurrent) {
                        this.$refs[this.tableOptions.ref].clearCurrentRow();
                    }
                }
            }
        },
        getSelection() {
            if (this.$refs[this.tableOptions.ref]) {
                if (this.tableOptions.multiSelect) {
                    return this.$refs[this.tableOptions.ref].getCheckboxRecords();
                }
                if (this.tableOptions.radioSelect) {
                    return this.$refs[this.tableOptions.ref].getRadioRecord();
                }
            }
            return undefined;
        },
        showEvent(evnt, options) {
            this.$refs.tableExport.showEvent(this, options);
        },
        getCurrentEvent() {
            // 用于 highlight-current-row，获取高亮状态行
            let ref = this.$refs[this.tableOptions.ref];
            let row = ref.getCurrentRecord();
            this.$emit("getCurrentEvent", { ref, row });
            this.$emit("event", { type: "getCurrentEvent", ref, row });
        },
        setCurrentEvent(row) {
            // 用于 highlight-current-row，设置某一行为高亮状态
            let ref = this.$refs[this.tableOptions.ref];
            ref.setCurrentRow(row);
        },
        getCheckboxRecords(row) {
            // 用于 highlight-current-row，设置某一行为高亮状态
            let ref = this.$refs[this.tableOptions.ref];
            return ref.getCheckboxRecords();
        },
        // setCurrentEvent (row) {
        //     // 用于 highlight-current-row，设置某一行为高亮状态
        //     let ref = this.$refs[this.tableOptions.ref];
        //     ref.setCurrentRow(row)
        // },
        // 用于 edit-config，激活行编辑，如果是 mode=cell 则默认激活第一个单元格
        setActiveRow(row) {
            let ref = this.$refs[this.tableOptions.ref];
            ref.setActiveRow(row);
            setTimeout(() => {
                this.scrollToRow();
            }, 50);
        },
        clearActive() {
            let ref = this.$refs[this.tableOptions.ref];
            return ref.clearActived();
        },
        scrollToRow(row) {
            let _this = this;
            let ref = this.$refs[this.tableOptions.ref];
            let container = _this.getActiveTabsContainer();
            if (_this.$utils.isNotEmpty(_this.tableOptions.container)) {
                container = $(container).find(_this.tableOptions.container);
            }
            // let table = $(container).find('.vxe_table_container').find('.table');
            let col = $(container).find(".vxe_table_container").find(".table").find(".col--actived");
            let tableBody;
            if (col.length) {
                if (ref.$refs.tableBody) {
                    tableBody = ref.$refs.tableBody.$el;
                } else return;
                let top = col[0].offsetTop;
                let colRect = col[0].getBoundingClientRect();
                // let tableRect = table[0].getBoundingClientRect()
                if (colRect.y > ref.lastScrollTop + tableBody.offsetHeight) {
                    ref.scrollTo(0, ref.lastScrollTop + 40);
                    // console.log("ref",ref)
                    ref.scrollTop -= 1;
                    // setTimeout(()=>{
                    //    _this.$forceUpdate()
                    // },10)
                }
            }
        },
        // 往表格插入临时数据（不支持深层结构），从第一行插入一行或多行新数据
        insert(rows) {
            let ref = this.$refs[this.tableOptions.ref];
            ref.insert(rows);
            let data = ref.getTableData().tableData;
            this.$emit("update:data", data);
            if (this.tableOptions.setData) {
                this.tableOptions.setData({ data, ref });
            }
        },
        // 往表格插入临时数据（不支持深层结构），从指定位置插入一行或多行；第二个参数：row 指定位置、null从第一行插入、-1 从最后插入
        insertAt(records, row) {
            let ref = this.$refs[this.tableOptions.ref];
            ref.insertAt(records, row);
            let data = ref.getTableData().tableData;
            this.$emit("update:data", data);
            if (this.tableOptions.setData) {
                this.tableOptions.setData({ data, ref });
            }
        },
        // 删除指定行数据（不支持深层结构），指定 row 或 [row, ...] 删除多条数据，如果为空则删除所有数据
        remove(rows) {
            let ref = this.$refs[this.tableOptions.ref];
            ref.remove(rows);
            let data = ref.getTableData().tableData;
            this.$emit("update:data", data);
            if (this.tableOptions.setData) {
                this.tableOptions.setData({ data, ref });
            }
        },
        // 删除复选框选中的行数据
        removeCheckboxRow(rows) {
            let ref = this.$refs[this.tableOptions.ref];
            ref.removeCheckboxRow();
            let data = ref.getTableData().tableData;
            this.$emit("update:data", data);
            if (this.tableOptions.setData) {
                this.tableOptions.setData({ data, ref });
            }
        },
        // 删除单选框选中的行数据（不支持深层结构）
        removeRadioRow(rows) {
            let ref = this.$refs[this.tableOptions.ref];
            ref.removeRadioRow();
            let data = ref.getTableData().tableData;
            this.$emit("update:data", data);
            if (this.tableOptions.setData) {
                this.tableOptions.setData({ data, ref });
            }
        },
        getActiveRow() {
            let ref = this.$refs[this.tableOptions.ref];
            if (ref) {
                return ref.getActiveRecord();
            }
            return null;
        },
        reloadRow(rows, record, field) {
            let ref = this.$refs[this.tableOptions.ref];
            if (ref) {
                ref.reloadRow(rows, record, field);
            }
        },
        updateStatus(slotParams) {
            let ref = this.$refs[this.tableOptions.ref];
            if (ref) {
                ref.updateStatus(slotParams);
            }
        },
        clearAll() {
            let ref = this.$refs[this.tableOptions.ref];
            return ref.clearAll();
        },
        isUpdateByRow(row) {
            let ref = this.$refs[this.tableOptions.ref];
            if (ref) {
                return ref.isUpdateByRow(row);
            }
            return false;
        },
        handleResizableChange({ $table }) {
            if ($table) {
                this.$store.dispatch('saveTableSetting', {
                    table: $table,
                    tableOptions: this.tableOptions,
                    route: this.$route,
                });
            }
        },
        handleCustomEvent({ type, $table }) {
            const _this = this;
            if (['confirm', 'reset'].indexOf(type) !== -1) {
                _this.$store.dispatch('saveTableSetting', {
                    table: $table,
                    tableOptions: _this.tableOptions,
                    route: _this.$route,
                    reset: type === 'reset',
                }).then(() => {
                    if (type === 'reset') {
                        $table.resetColumn({ visible: true, resizable: false });
                    }
                });
            }
        },
        exportTable(params = {}, outputName = '导出') {
            const _this = this;
            let titleField = eachTableField(_this.tableOptions.columns);
            if (typeof params.titleField === 'function') {
                titleField = params.titleField(titleField);
                delete params.titleField;
            }
            exportExcel4MultiHead(params, titleField, outputName);
        },
    },
};
</script>

<style scoped>
@import "index.css";
</style>
